<template>
	<view style="margin-top: 100px;">
		<text style="margin-top: 100px;">蓝牙测试</text>
		<br />
		<text>{{msg}}</text>
		<br />
		<text>{{blueToothInfo}}</text>
		<br />
		<text>{{watchNewDevInfo}}</text>
		<br />
		<text>历史设备</text>
		<text>{{hisDevList}}</text>
	</view>
</template>

<script>
	import {
		defineComponent,
		onMounted,
		ref
	} from 'vue'
	export default defineComponent({
		name: 'BlueToothTestPage'
	})
</script>
<script setup>
	const msg = ref('等待')


const blueToothInfo = ref('')

const watchNewDevInfo = ref('')

const hisDevList = ref('')



	// 初始化蓝牙模块
	const initBlueToothModule = () => {
		uni.openBluetoothAdapter({
			success: () => {
				console.log('初始化蓝牙模块成功!');
				msg.value = '成功'
				searchBluetoothDev()
			},
			fail: (err) => {
				console.log('初始化蓝牙模块失败!', err);
				msg.value = '失败'
			}
		})
	}


	// 搜索附近蓝牙设备
	const searchBluetoothDev = () => {
		// 以微信硬件平台的蓝牙智能灯为例，主服务的 UUID 是 FEE7。传入这个参数，只搜索主服务 UUID 为 FEE7 的设备
		uni.startBluetoothDevicesDiscovery({
			success(res) {
				console.log(res)
				blueToothInfo.value = JSON.stringify(res)
				msg.value = '搜索蓝牙设备完成'
				watchNewDev()
			},
			fail(err) {
				console.log(err)
				msg.value = '搜索蓝牙设备失败'
			}
		})
	}
	
	// 监听蓝牙新设备
	const watchNewDev = ()=>{
		uni.onBluetoothDeviceFound((res)=>{
			watchNewDevInfo.value = JSON.stringify(res)
			res.devices.forEach((item)=>{
				if(item.name.includes('EDIFIER')){
					hisDevList.value = hisDevList.value + JSON.stringify(item)
				}
			})
			
			
		})
	}

	onMounted(() => {
		console.log('蓝牙测试页面');
		initBlueToothModule()
		console.log(uni);
	})
</script>

<style lang="scss" scoped></style>